import {
	baseURL, clientId
} from '@/config/config.js'

// 请求拦截器
const httpInterceptor = {
	invoke(options) {
		// 1. 拼接基础请求地址
		options.url = `${baseURL}${options.url}`

		// 2. 设置超时时间
		options.timeout = 10000

		// 3. 添加小程序端请求标识
		options.header = {
            clientid: clientId,
			...options.header
		}

		// 4. 添加token
		const token = uni.getStorageSync('token');
		
		if (token) {
			options.header.Authorization = `Bearer ${token}`
		}
	}
}

// 注册拦截器
uni.addInterceptor('request', httpInterceptor)
// uni.addInterceptor('uploadFile', httpInterceptor)

// 封装请求方法
export const http = {
	/**
	 * 请求函数
	 * @param {Object} options - 请求配置
	 * @returns {Promise} 请求结果
	 */
	async request(options) {
		// 显示加载中，除非明确指定不显示
		if (options.loading !== false) {
			uni.showLoading({
				title: options.loadingText || '数据加载中...',
				mask: true
			})
		}

		try {
			const res = await uni.request({
				...options,
				// 设置请求头
				header: {
					'Content-Type': 'application/json',
					...options.header
				}
			})
			
			uni.hideLoading();

			// 状态码2xx表示成功
			if (res.statusCode == 200 && res.data.code == 200) {
				return res.data
			}

			// 处理401未授权的情况
			if (res.data.code === 401) {
				// 清除token
				uni.removeStorageSync('token')
				// 跳转到登录页
				uni.navigateTo({
					url: '/pages/login'
				})
				return Promise.reject(new Error('请先登录'))
			}

			// 其他错误
			uni.showToast({
				icon: 'none',
				title: res.data?.msg || '请求失败'
			})
			return Promise.reject(res.data)

		} catch (err) {
			// 发生错误时也要隐藏loading
			if (options.loading !== false) {
				uni.hideLoading()
			}
			
			uni.showToast({
				icon: 'none',
				title: '网络错误，请稍后重试'
			})
			return Promise.reject(err)
		}
	},

	// 新增上传文件方法，支持进度回调  uploadFileWithProgress(url, filePath, name, formData = {}, onProgress = () => {}) {
	uploadFileWithProgress(url, filePath, name, formData = {}, onProgress = () => {}, loading = true) {
		if (loading) {
			uni.showLoading({
				title: '上传中...',
				mask: true
			})
		}

		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: `${baseURL}${url}`,
				filePath,
				name,
				formData,
				header: {
					...formData.header
				},
				success: (uploadFileRes) => {
					if (loading) {
						uni.hideLoading()
					}
					console.log(uploadFileRes);
					const data = JSON.parse(uploadFileRes.data);
					if (uploadFileRes.statusCode == 200 && data.code == 200) {
						resolve(data);
					} else {
						uni.showToast({
							icon: 'none',
							title: data?.msg || '上传失败'
						});
						reject(data);
					}
				},
				fail: (err) => {
					if (loading) {
						uni.hideLoading()
					}
					
					uni.showToast({
						icon: 'none',
						title: '网络错误，请稍后重试'
					});
					reject(err);
				}
			});

			// 监听上传进度变化
			uploadTask.onProgressUpdate((res) => {
				onProgress(res);
			});
		});
	},

	// GET请求
	get(url, params = {}) {
		return this.request({
			url,
			method: 'GET',
			data: params
		})
	},

	// POST请求
	post(url, data = {}) {
		return this.request({
			url,
			method: 'POST',
			data
		})
	},

	// PUT请求
	put(url, data = {}) {
		return this.request({
			url,
			method: 'PUT',
			data
		})
	},

	// DELETE请求
	delete(url, data = {}) {
		return this.request({
			url,
			method: 'DELETE',
			data
		})
	},
	
	upload(filePath) {
		// 4. 添加token
		const token = uni.getStorageSync('token');
		return new Promise((resolve, reject)=>{
			uni.uploadFile({
				url: `${baseURL}/upload/standard`,
				filePath,
				name: 'file',
				header: {
					clientid: clientId,
					Authorization: token ? ('Bearer ' + token) : ''
				},
				success(d) {
					console.log(d);
					if (d.data) {
						const data = JSON.parse(d.data);
						if (data.code == 200) {
							resolve(data.data);
						} else {
							reject(data);
						}
					} else {
						reject(d);
					}
				}
			})
		})
	}
}